
package com.walkingfiles.alfresco

import org.apache.http.client.utils.URIBuilder
import org.apache.http.util.EntityUtils
import org.apache.http.impl.client.HttpClients
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.BasicResponseHandler
import org.apache.http.NameValuePair
import org.apache.http.message.BasicNameValuePair
import org.apache.http.client.entity.UrlEncodedFormEntity

import groovy.json.JsonSlurper

class AlfrescoServiceConnection {

    def loginURL
    def alfrescoConfig  

    AlfrescoServiceConnection(alfrescoConfig) {
        this.alfrescoConfig = alfrescoConfig
        def serviceURL = "${alfrescoConfig.baseURL}${alfrescoConfig.serviceURL}"
        loginURL = new URIBuilder(serviceURL + '/api/login')
    }

    def getClient(user, password) {
        URI uri = loginURL
		                .setParameter("u", user)
		                .setParameter("pw", password)
		                .build()
        def httpclient = HttpClients.createDefault()
        def httpget = new HttpGet(uri)
        def responseHandler = new BasicResponseHandler()
        // TODO: Handle errors
        def response = httpclient.execute(httpget)    
        def ticket = new XmlSlurper().parse(response.getEntity().getContent())
        new AlfrescoHttpClient(alfrescoConfig, ticket.text())
    }

}

class AlfrescoHttpClient {

    def alfrescoConfig
    def serviceURL
    def baseURL
    def ticket

    AlfrescoHttpClient(alfrescoConfig, ticket) {
        this.alfrescoConfig = alfrescoConfig
        baseURL = alfrescoConfig.baseURL
        serviceURL = alfrescoConfig.serviceURL
        this.ticket = ticket
    }

    def getTicketParam(relativeURL) {
        if (relativeURL.startsWith(alfrescoConfig.serviceURL)) {
            "alf_ticket"
        } else {
            "ticket"
        }
    }

    def getUrlWithTicket(relativeURL) {
        def url = "${baseURL}${relativeURL}"
        new URIBuilder(url)
                .setParameter(getTicketParam(relativeURL), ticket)
    }

    def get(relativeURL, parameters=[:]) {
        
        def alfrescoURL = getUrlWithTicket(relativeURL)

        parameters.each { paramName, paramValue -> 
            alfrescoURL.setParameter(paramName, paramValue)
        }
        def httpClient = HttpClients.createDefault()
        def httpGet = new HttpGet(alfrescoURL.build())
        // TODO: Handle errors
        httpClient.execute(httpGet)    
    }

    def post(relativeURL, parameters=[:]) {        

        def alfrescoURL = getUrlWithTicket(relativeURL)
        def httpClient = HttpClients.createDefault()
        def httpPost = new HttpPost(alfrescoURL.build())

        def postParameters = new ArrayList<NameValuePair>()

        parameters.each { paramName, paramValue -> 
            postParameters.add(new BasicNameValuePair(paramName, paramValue))
        }
        
        httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
        
        httpClient.execute(httpPost)    
        
    }

    def serviceGet(wsURL, parameters=[:]) {
        def absoluteWsURL = "${serviceURL}${wsURL}"
        get(absoluteWsURL, parameters)
    }
    
    def servicePost(wsURL, parameters=[:]) {
        def absoluteWsURL = "${serviceURL}${wsURL}"
        post(absoluteWsURL, parameters)
    }

    def getContent(folderPath, recursive=false) {
        def wsURL = '/walkingfiles/getcontent.json'
        def parameters = [folder: folderPath]
        if (recursive) {
            parameters['recursive'] = 'yes'
        }
    	def response = serviceGet(wsURL, parameters) 
        def items = EntityUtils.toString(response.getEntity())
        new JsonSlurper().parseText(items)
    }

    def createFolder(folderPath) {        
        def wsURL = '/walkingfiles/createfolder.json'
        def parameters = [folder: folderPath]
    	def response = servicePost(wsURL, parameters) 
        def items = EntityUtils.toString(response.getEntity())
        new JsonSlurper().parseText(items)
    }
   
}

